package com.bwie.service.impl;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.bwie.config.TwoOssConfig;
import com.bwie.service.PictureService;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private TwoOssConfig twoOssConfig;

    private static String[] STRING_TYPE=new String[]{
            "jpg",
            "png",
            "jpeg"
    };
    @Autowired
    private OSSClient ossClient;

    @Override
    public String uploadImage(MultipartFile file) {

        String url="";

        Boolean flag=false;

        for (String s : STRING_TYPE) {

            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),s)){
                flag=true;
                break;
            }
        }
        if (!flag){
            return url;
        }

        String originalFilename = file.getOriginalFilename();

        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

        String dataTime = new SimpleDateFormat("yyyy/MM/dd").format(new Date());

       String newFileName= twoOssConfig.getFileHost()+"/"+dataTime+"/"+
               UUID.randomUUID().toString().replace("-","")+fileType;


        try {
            InputStream inputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            ossClient.putObject(twoOssConfig.getBucketName(),newFileName,inputStream,objectMetadata);

            return "http://"+twoOssConfig.getBucketName()+"."+twoOssConfig.getEndpoint()+"/"+newFileName;
        } catch (IOException e) {
            e.printStackTrace();

        }
        return url;

    }
}
